package com.v.im.websocketservice.service;

import com.v.im.businessapi.dto.resultDTO.ImChatGroupResultDTO;
import com.v.im.businessapi.feign.ImChatGroupClientService;
import com.v.im.commonmodule.utils.bean.CurrentUserInfo;
import com.v.im.commonmodule.utils.constants.RedisKeyContants;
import com.v.im.commonmodule.utils.utils.UserHeaderUtil;
import com.v.im.websocketservice.bean.SocketUserInfo;
import com.v.im.websocketservice.config.KafkaConfig;
import com.v.im.websocketservice.constants.Constants;
import com.v.im.websocketservice.netty.client.INettyClient;
import com.v.im.websocketservice.websocket.ImWebSocket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wym
 * @create 2019-03-08 20:14
 **/
@Slf4j
@Component
public class WebSocketService {

    @Resource
    private KafkaConfig kafkaConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    protected ImChatGroupClientService imChatGroupClientService;

    @Autowired
    private INettyClient nettyClient;

    protected static ConcurrentHashMap<String, SocketUserInfo> userInfoMap;

    protected static ConcurrentHashMap<String, List<SocketUserInfo>> imGroupMap;


    /**
     *  绑定用户信息
     *
     * @param imWebSocket
     */

    public void bindUserSocket(ImWebSocket imWebSocket){
        SocketUserInfo socketUserInfo = getSocketUserInfo(imWebSocket);
        addGroupWebSocket(socketUserInfo);
        log.info("在线人数为" + userInfoMap.size());
    }

    /**
     *  获取用户信息
     *
     * @return
     */
    public SocketUserInfo getSocketUserInfo(ImWebSocket imWebSocket) {
        CurrentUserInfo currentUserInfo = getCurrentUserInfo(imWebSocket);
        if (currentUserInfo == null) {
            return null;
        }
        SocketUserInfo userInfo = new SocketUserInfo();
        String userId = currentUserInfo.getUserId();
        userInfo.setImWebSocket(imWebSocket);
        userInfo.setUserId(userId);
        userInfoMap.put(userId, userInfo);
        //用户和kafka topic添加缓存
        stringRedisTemplate.opsForValue().set(RedisKeyContants.USER_TOPIC + userId, kafkaConfig.getTopic());
        return userInfo;
    }


    /**
     *  解除用户绑定
     *
     * @param imWebSocket
     */

    public void unBindUserSocket (ImWebSocket imWebSocket) {
        CurrentUserInfo currentUserInfo = getCurrentUserInfo(imWebSocket);
        if (currentUserInfo == null) {
            return;
        }
        String userId = currentUserInfo.getUserId();
        //删除本地缓存
        userInfoMap.remove(userId);
        //删除redis缓存
        stringRedisTemplate.delete(RedisKeyContants.USER_TOPIC + userId);
        //todo 清楚群缓存
    }

    private CurrentUserInfo getCurrentUserInfo(ImWebSocket imWebSocket){
        Object headToken =  imWebSocket.endpointConfig.getUserProperties().get(Constants.USER_INFO);
        if (headToken == null) {
            return null;
        }
        return UserHeaderUtil.getCurrentUserInfo(headToken.toString());
    }

   public void sendImServiceMessage(String message){
       nettyClient.send(message);
      log.info("来自客户端的消息:" + message);
   }

    /**
     *  用户初始化群组
     *
     * @param socketUser
     */
    public void addGroupWebSocket(SocketUserInfo socketUser) {
        List<ImChatGroupResultDTO> imChatGroupResultDTOS = imChatGroupClientService.getUserGroups(socketUser.getUserId());
        if (CollectionUtils.isNotEmpty(imChatGroupResultDTOS)) {
            for (ImChatGroupResultDTO imChatGroupResultDTO : imChatGroupResultDTOS) {
                List<SocketUserInfo> socketUserInfos = imGroupMap.get(imChatGroupResultDTO.getId());
                if (CollectionUtils.isEmpty(socketUserInfos)) {
                    socketUserInfos = new ArrayList<>();
                }
                socketUserInfos.add(socketUser);
                imGroupMap.put(imChatGroupResultDTO.getId(), socketUserInfos);
            }
        }
    }





    /**
     * 群聊
     * @param message
     * @throws IOException
     */
//    public static void sendCrowdMessage(Message message) throws IOException {
//        if (message != null && StringUtils.isNotBlank(message.getId())) {
//            if (groupWebSocketMap.size() > 0 && CollectionUtils.isNotEmpty(groupWebSocketMap.get(message.getId()))) {
//                for (ImWebSocket imWebSocket : groupWebSocketMap.get(message.getId())) {
//                    imWebSocket.sendMessage(imWebSocket,JSON.toJSONString(message));
//                }
//            }
//        }
//    }


}
